/*global jQuery: false, console: false */

/*members addInputType, ajax, append, async, attr, content, data, 
 dataType, each, editable, element, id, log, name, split, submit,
 success, text, trim, url, val
 */

jQuery.editable.addInputType("ticker_symbol", {

    element: function (settings, original) {
        var input = jQuery("<input id=\"ticker_symbol_name_\" />"),
                ticker_symbol_select = jQuery('<select id="ticker_symbol_select_" />'),
                hidden = jQuery('<input type="hidden" />');

        jQuery.ajax({
            url: "/ticker_symbols/",
            dataType: 'json',
            async: false,
            data: {},
            success: function (data, textStatus) {
                jQuery.each(data, function (i, item) {
                    var option = jQuery("<option />").val(item.id).append(item.name);
                    ticker_symbol_select.append(option);
                });
            }
        });
        jQuery(this).append(input);
        jQuery(this).append(ticker_symbol_select);
        jQuery(this).append($('<input type="button" value="Delete" class="rm" />'));
        jQuery(this).append(hidden);
        return (hidden);
    },

    content: function (string, settings, original) {
        var stock_exchange, ticker_symbol;
        if (string !== '') {
            stock_exchange = string.split("(")[1].split(")")[0].trim();
            ticker_symbol = string.split("(")[0].trim();
            jQuery("#ticker_symbol_name_", this).val(ticker_symbol);
            jQuery('#ticker_symbol_select_ option:contains(' + stock_exchange + ')', this).attr('selected', 'selected');
        }
    },
    /* Call before submit hook. */
    submit: function (settings, original) {
        var value = jQuery('#ticker_symbol_name_').val() + '|' + jQuery('#ticker_symbol_select_').val() + '|' + jQuery('#ticker_symbol_select_ option:selected').text();
        jQuery('input', this).val(value);
    }
});


jQuery.editable.addInputType("area_of_expertise", {
    element: function (settings, original) {
        var areas = jQuery("<select id=\"areas_of_expertise_\" />"),
                hidden = jQuery('<input type="hidden" />');
        jQuery.ajax({
            url: "/areas_of_expertise/",
            dataType: 'json',
            async: false,
            data: {},
            success: function (data, textStatus) {
                jQuery.each(data, function (i, item) {
                    var option = jQuery("<option />").val(item.id).append(item.name);
                    areas.append(option);
                });
                console.log("options appended");
            }
        });
        jQuery(this).append(areas);
        jQuery(this).append(hidden);
        return (hidden);
    },
    /* Call before submit hook. */
    submit: function (settings, original) {
        var value = jQuery("#areas_of_expertise_").val() + "|add";
        jQuery("input", this).val(value);
    }
});

